#pragma once

#include "Log.hpp"
#include <string>
#include <unordered_map>
#include <fstream>
#include "InetAddr.hpp"

using namespace LogModule;

const std::string defaultdict = "./dictionary.txt";
const std::string sep = ":";

class Dict
{

public:
    Dict(const std::string &dict_path = defaultdict)
        : _dict_path(dict_path)
    {
    }

    bool LoadDict()
    {
        std::ifstream in (_dict_path);
        if(!in.is_open())
        {
            LOG(LogLevel::FATAL) << "LoadDict failed";
            return false;
        }

        std::string line;
        while(std::getline(in , line))
        {
            auto pos = line.find(sep);
            if(pos == std::string::npos)
            {
                LOG(LogLevel::ERROR) << "加载" << line << "错误" ;
                continue;
            }

            std::string english = line.substr(0 , pos);
            std::string chinese = line.substr(pos + sep.size());
            if(english.empty() || chinese.empty())
            {
                LOG(LogLevel::ERROR) << line <<"内容缺失";
                continue;
            }

            _dict.insert(std::make_pair(english , chinese));
            LOG(LogLevel::INFO) << line <<"加载成功";
        }
        in.close();
        return true;
    }


    std::string Translate(const std::string& word , InetAddr addr)
    {

        auto iter = _dict.find(word);
        if(iter == _dict.end())
        {
            LOG(LogLevel::INFO) << "[" << addr.GetIP() << ":" << addr.GetPort() << "]" << word << "->" << "None";
            return "None";
        }

        LOG(LogLevel::INFO) << "[" << addr.GetIP() <<  "]" << addr.GetPort() <<word << "->"  << iter->second;
        return iter->second;
    }
    ~Dict()
    {
    }

private:
    std::string _dict_path;
    std::unordered_map<std::string, std::string> _dict;
};